<template>
  <div style="background-color: #f6f6f6;height: 100vh;margin-bottom: 50rem;">
    <div>
      <button class="goBack" @click="goBack">
        <van-icon name="arrow-left" />
      </button>
      <div class="shpcar">
        确认订单
      </div>
      <van-cell  @click="showShare = true" >
      <div class="edit"><van-icon name="share-o" /></div>
    </van-cell>
      <van-share-sheet v-model:show="showShare" title="立即分享给好友" :options="options" @select="onSelect" />
    </div>
    <!-- 收货地址 -->
    <van-cell title="展示弹出层" is-link @click="showPopup">
      <div class="address">
        <van-icon name="location-o" />
        <div v-if="currentAddress" style="margin-left: 10rem;">
          <div style="font-weight: bold;">{{ currentAddress.name }} {{ currentAddress.tel }}</div>
          <div style="font-weight: 100;font-size: 13rem;">{{ currentAddress.province }} {{ currentAddress.city }} {{
            currentAddress.county }} {{
              currentAddress.detail }}</div>
        </div>
        <div v-else>
          <div>收货地址</div>
        </div>
        <div style="position: absolute;right: 5rem;">
          <van-icon name="arrow" />
        </div>
      </div>
    </van-cell>
    <van-popup v-model:show="show" round position="bottom" :style="{ height: '80%' }" style="box-sizing: border-box;">
      <div v-if="resss && addressStore.getAllAddresses().length <= 0">
        <van-image width="80%" height="auto" style="margin-left: 38rem;margin-top: 35rem;"
          src="https://s10.mogucdn.com/p2/170222/upload_1ga8374ha4c1e315k293bce18d3b9_514x258.png" />
        <div style="text-align: center;color: #999;">您还没没收货地址哦~</div>
      </div>
      <button class="addAddress" @click="goToAddress">+ 新增地址</button>
      <div v-if="!resss">
        <van-address-edit :area-list="areaList" show-set-default show-search-result :search-result="searchResult"
          :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave" @delete="onDelete"
          @change-detail="onChangeDetail" />
        <button class="addAddress" @click="upAddress">取消</button>
      </div>
      <div class="addressitem" v-if="addressStore.getAllAddresses().length > 0 && resss"
        v-for="address in addressStore.getAllAddresses()" :key="address.id">
        <div @click="onAddressClick(address)">
          <p class="addname">{{ address.name }} {{ address.tel }}</p>
          <p class="adddizhi">{{ address.province }} {{ address.city }} {{ address.county }} {{ address.detail }}</p>
          <!-- <button @click="addressStore.deleteAddress(address.areaCode)">删除</button> -->

        </div>
        <button @click="onDelete(address)">删除</button>
      </div>
    </van-popup>
    <!-- 内容 -->
    <div style="margin-top: 5rem;margin-bottom: 50rem;background-color:white;padding-bottom: 50rem;">
      <div v-for="store in groupedItems" :key="store.storeName" class="caritem">
        <div>
          <span class="storename">{{ store.storeName }}</span>
        </div>
        <div v-for="item in store.items" :key="item.id" class="item">
          <van-card :num="item.num" :price="item.price" :title="item.title" :thumb="item.thumb" class="goodscard" />
          <div class="desc">
            <div v-for="(value, key) in item.desc" :key="key">
              {{ key }}: {{ value }}
            </div>
          </div>
        </div>
        <div class="order-details">
          <div><span>快递运费</span><span style="color: #999;">默认快递</span><span
              style="margin: 0;margin-left: 130rem;">￥0.00</span></div>
          <div><span>意外换新</span><span style="color: #999;">衣服出现意外破损可换新</span><input type="radio"
              style="margin: 0;margin-left: 60rem;"></div>
          <div><span>退货补运费</span><span style="margin: 0;margin-left: 132rem;">退货预计补贴7.00</span></div>
          <div><span>延误必配</span><span style="margin: 0;margin-left: 200rem;">商家赠送</span></div>
          <div><span style="margin-right: 27rem;">订单备注</span><input type="text" placeholder="有什么想对商家说的可以写在这里哦~"></div>
          <div class="total-price" v-if="calculateStoreTotal(store) !== 0"><span style="color: #474857;margin-right: 0;">店铺合计:</span> <span
              style="margin-right: 0;">￥{{ calculateStoreTotal(store).toFixed(2) }}</span></div>
              <!-- +----------------------------------- -->
          <!-- <div class="total-price"><span style="color: #474857;margin-right: 0;">店铺合计:</span> <span
              style="margin-right: 0;">￥{{ calculateStoreTotal(store) }}</span></div> -->
              <!-- ------------------------------------ -->
        </div>
      </div>
      <div style="height: 10rem;background-color: #f6f6f6;"></div>
      <!-- 优惠券单元格 -->
      <van-coupon-cell :coupons="coupons" :chosen-coupon="chosenCoupon" @click="showList = true" />
      <!-- 优惠券列表 -->
      <van-popup v-model:show="showList" round position="bottom" style="height: 90%; padding-top: 4px;">
        <van-coupon-list :coupons="coupons" :chosen-coupon="chosenCoupon" :disabled-coupons="disabledCoupons"
          @change="onChange" @exchange="onExchange" />
      </van-popup>
      <div style="height: 10rem;background-color: #f6f6f6;"></div>
      <van-cell title="展示弹出层" is-link @click="onSubmit">
        <!-- <van-submit-bar :price="totalPrice * 100" button-text="提交订单" /> -->
        <van-submit-bar :price="totalPrice * 100" button-text="提交订单" />
      </van-cell>
    </div>
    <van-popup v-model:show="showPayment" round position="bottom" :style="{ height: '60%' }">
      <div class="payment-page" v-if="passinput">
        <div>
          <div class="shpcar" style="line-height: 8rem;height: 24rem;font-size: 16rem;">
            <button class="goBack" style="margin-top: 0;">
              <van-icon name="cross" />
            </button>
            收银台
          </div>
        </div>
        <div
          style="width: 100%;display: flex;justify-content: space-between; padding: 10rem;border-bottom: 1rem solid rgb(218 218 218);color: rgb(107 105 105);;">
          <span>支付方式: </span><span>{{ paymentMethod }}</span>
        </div>
        <div style="width: 100%;display: flex;justify-content: space-between;padding: 10rem;color: rgb(107 105 105);">
          <span>支付金额:
          </span><span style="color: black;font-size: 20rem;">¥{{ totalPrice.toFixed(2) }}</span>
        </div>
        <van-button type="primary" @click="confirmPayment" block
          style="margin-top: 210rem;background-color: #ff5777;border: none;">确认支付</van-button>
      </div>
      <div v-else>
        <!-- 密码输入框 -->
        <van-password-input :value="value" :focused="showKeyboard" @focus="showKeyboard = true"
          style="margin-top: 50rem;" />
        <!-- 数字键盘 -->
        <van-number-keyboard v-model="value" :show="showKeyboard" @blur="showKeyboard = false" @input="pswSubmit" />
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import { Icon as VanIcon, Toast } from 'vant';
import { areaList } from '@vant/area-data';
import { useAddressStore } from '@/stores/addressStore';
import { useRouter } from 'vue-router';

const router = useRouter(); // 使用 useRouter 钩子
const route = useRoute();

const items = ref([]);
const goBack = () => {
  router.go(-1); // 使用 router 对象的 go 方法返回上一页
};


import { useGwcStore } from '@/stores/gwc'; // 确保路径正确
const gwcStore = useGwcStore();
const groupedItems = computed(() => gwcStore.groupCartItemsByStore());
// 解析传递的商品信息
const parsedItems = computed(() => {
  try {
    const itemsString = route.query.items || route.params.cartItems;
    if (itemsString) {
      return JSON.parse(decodeURIComponent(itemsString));
    }
    return [];
  } catch (e) {
    Toast('解析商品信息出错');
    return [];
  }
});


// 计算总价，考虑优惠券
// const totalPrice = computed(() => {
//   // 计算 parsedItems.value 中的总价
//   const basePriceFromParsedItems = parsedItems.value.reduce((sum, item) => sum + (item.price * item.num), 0);

//   // 如果 parsedItems.value 中的总价为 0，则计算 groupedItems 中的总价
//   if (basePriceFromParsedItems === 0) {
//     // 计算 groupedItems 中的总价
//     const basePriceFromGroupedItems = groupedItems.value.reduce((total, store) => {
//       return store.items.reduce((sum, item) => sum + (item.price * item.num), total);
//     }, 0);

//     // 处理优惠券逻辑（假设你有 coupons 和 chosenCoupon 的相关逻辑）
//     // const discount = 0; // 这里可以根据你的优惠券逻辑计算折扣
//     return basePriceFromGroupedItems
//   } else {
//     // 处理优惠券逻辑（假设你有 coupons 和 chosenCoupon 的相关逻辑）
//     const discount = parseFloat(coupons.value[chosenCoupon.value].valueDesc),
//     return basePriceFromParsedItems - discount;
//   }
// });
// 计算总价，考虑优惠券
// const totalPrice = computed(() => {
//   const basePriceFromParsedItems = parsedItems.value.reduce((sum, item) => sum + item.price * item.num, 0);
//   if (chosenCoupon.value === -1 || !coupons.value[chosenCoupon.value]) {
//     return basePriceFromParsedItems;
//   }
//   const discount = parseFloat(coupons.value[chosenCoupon.value].valueDesc);
//   return basePriceFromParsedItems - discount;
// });
const totalPrice = computed(() => {
  // 首先尝试从 parsedItems 获取总价
  const basePriceFromParsedItems = parsedItems.value.reduce((sum, item) => sum + item.price * item.num, 0);

  // 如果 parsedItems 没有商品信息，则从 groupedItems 获取总价
  let totalPrice = basePriceFromParsedItems;
  if (totalPrice === 0) {
    totalPrice = groupedItems.value.reduce((total, store) => {
      return store.items.reduce((sum, item) => sum + item.price * item.num, total);
    }, 0);
  }

  // 检查是否有选中的优惠券并计算折扣
  if (chosenCoupon.value !== -1 && coupons.value[chosenCoupon.value]) {
    const discount = parseFloat(coupons.value[chosenCoupon.value].valueDesc);
    totalPrice -= discount;
  }

  return totalPrice;
});
// 计算每个店铺的总价
const calculateStoreTotal = (store) => {
  console.log('Calculating total for store:', store.storeName);
  return store.items
    .filter(item => item.selected)
    .reduce((sum, item) => {
      console.log('Adding item to total:', item.title, 'Price:', item.price, 'Quantity:', item.num);
      return sum + item.price * item.num;
    }, 0);
};
// 在组件加载时解析商品信息并存储到 Pinia store
onMounted(() => {
  items.value = parsedItems.value; // 将解析后的  值给 items
  if (items.value.length === 0) {

  } else {
    // 将 items 存储到 Pinia store
    gwcStore.setCartItems(items.value);
  }
});

// 弹出层
const show = ref(false);
const showPopup = () => {
  show.value = true;
};

// 地址编辑
const resss = ref(true);
const goToAddress = () => {
  resss.value = false;
};
const upAddress = () => {
  resss.value = true;
};
// 地址编辑
const searchResult = ref<{ name: string; address: string }[]>([]);

const addressStore = useAddressStore();
const onSave = (detail) => {
  console.log('保存的地址详情:', detail);
  // 假设 detail 包含 name 和 tel 属性
  addressStore.addAddress({
    name: detail.name,
    tel: detail.tel,
    province: detail.province,
    city: detail.city,
    county: detail.county,
    detail: detail.addressDetail,
    areaCode: detail.areaCode,
  });
  resss.value = true;
};
const onDelete = (address) => {
  console.log(`Deleting address with areaCode: ${address.areaCode}`); // 调试日志
  addressStore.deleteAddress(address.areaCode); // 根据 areaCode 删除地址
  Toast('地址已删除');
};
const onChangeDetail = (val: string) => {
  if (val) {
    searchResult.value = [
      {
        name: '黄龙万科中心',
        address: '杭州市西湖区',
      },
    ];
  } else {
    searchResult.value = [];
  }
};

//当前选中的地址
const currentAddress = ref(null);
const onAddressClick = (address) => {
  currentAddress.value = address;
  show.value = false;
};


//支付
const showPayment = ref(false);
const paymentMethod = ref('支付宝'); // 假设支付方式为支付宝
const passinput = ref(true);
const confirmPayment = () => {
  // 这里可以添加支付逻辑，比如调用支付接口
  // Toast('支付成功');
  // showPayment.value = false; // 关闭支付页面
  passinput.value = false;
};

const onSubmit = () => {
  // if (!items.value.length) {
  //   Toast('请选择要结算的商品');
  //   return;
  // }
  console.log(123);

  showPayment.value = true; // 显示支付页面
};

//密码输入
const value = ref('');
const showKeyboard = ref(true);
const pswSubmit = () => {
  // 在这里处理密码输入的逻辑，例如调用支付接口
  // Toast('支付成功');
  // showPayment.value = false; // 关闭支付页面

};


//分享
const showShare = ref(false);
const options = [
  { name: '微信', icon: 'wechat' },
  { name: '微博', icon: 'weibo' },
  { name: '复制链接', icon: 'link' },
  { name: '分享海报', icon: 'poster' },
  { name: '二维码', icon: 'qrcode' },
];

const onSelect = (option) => {
  Toast(option.name);
  showShare.value = false;
};

watch(value, (newValue) => {
  if (newValue.length === 6) {
    if (newValue === '123456') {
      // 密码正确，继续执行支付逻辑
      passinput.value = true;
      showPayment.value = false; // 关闭支付页面
      value.value = '';

      // 保存到新的本地存储键中，例如 'selectedItemsHistory'
      const itemsString = localStorage.getItem('selectedItems');
      if (itemsString) {
        localStorage.setItem('selectedItemsHistory', itemsString);
      }

      // 清空路由参数
      router.replace({ path: router.currentRoute.value.path, query: {} });

      // 清空本地存储
      localStorage.removeItem('selectedItems');

      // 转跳到发货页面，并传递selectedItemsHistory数据
      router.push({
        path: '/shipment',
        query: {
          paymentData: encodeURIComponent(localStorage.getItem('selectedItemsHistory') || '')
        }
      });

      Toast('支付成功');
    } else {
      value.value = '';
      Toast('密码错误');
    }
  }
});


//优惠券
const coupon = {
  available: 1,
  condition: '无门槛\n最多优惠12元',
  reason: '',
  value: 150,
  name: '优惠券名称',
  startAt: 1489104000,
  endAt: 1514592000,
  valueDesc: '1.5',
  unitDesc: '元',
};

const coupons = ref([coupon]);
const showList = ref(false);
const chosenCoupon = ref(-1);

const onChange = (index) => {
  showList.value = false;
  chosenCoupon.value = index;
};
const onExchange = (code) => {
  coupons.value.push(coupon);
};
// 在组件加载时获取地址信息
onMounted(() => {
  const itemsString = localStorage.getItem('selectedItems');
  if (itemsString) {
    items.value = JSON.parse(itemsString);
  }
});



</script>

<style lang="less" scoped>
* {
  box-sizing: border-box;
}

.van-card {
  background: white;
}

.goBack {
  position: absolute;
  top: 15px;
  /* 调整为合适的像素值 */
  left: 20px;
  /* 调整为合适的像素值 */
  background-color: rgba(255, 255, 255, 0);
  border: none;
  font-size: 14px;
  /* 调整为合适的像素值 */
}

.shpcar {
  width: 100%;
  height: 44rem;
  text-align: center;
  font-size: 20rem;
  line-height: 44rem;
  border-bottom: 1rem solid #d1cdcd;
  color: #6f6f6f;
  background-color: white;
}

.edit {
  position: absolute;
  right: 20rem;
  top: 10rem;
  color: #6f6f6f;
}

.address {
  display: flex;
  align-items: center;
  padding: 10rem;
  border-bottom: 1rem solid #d1cdcd;
  background: #fff url(https://s10.mogucdn.com/p2/170214/126946420_07l7d36300234hlef16ggj1275537_88x10.png) repeat-x;
  background-size: 6%;
}

.addAddress {
  width: 92%;
  height: 44rem;
  background: #ffffff;
  border: 1rem solid #d1cdcd;
  text-align: center;
  line-height: 40rem;
  position: absolute;
  bottom: 143rem;
  left: 15rem;
  border-radius: 20rem;
  color: #ff5777;
}

.addressitem {
  margin: 10rem 15rem;
  background-color: #fff;
  border: 1px solid #b3b1b1;
  border-radius: 5rem;
  color: #6f6f6f;

  .addname {
    margin: 5rem;
  }

  .adddizhi {
    margin: 5rem;
    border-bottom: 1rem solid #dfdbdb;
  }

  button {
    border: none;
    background-color: #ffffff00;
  }
}

.caritem {
  background-color: #ffffff;
  height: auto;
  border: 1rem solid #d1cdcd;
  margin-top: 5rem;
  padding-top: 10rem;
  position: relative;
.item{
  position: relative;
}
  .desc {
    position: absolute;
    left: 107rem;
    font-size: 12rem;
    color: #999;
    top: 43rem;
    display: flex;
    width: 220rem;
    flex-wrap: wrap;

    div {
      padding: 0 5rem;
    }
  }

  // border-radius: 10rem;
  .storename {
    padding: 20rem;
  }
}

.caritem:nth-child(1) {
  margin-top: 0;
}

.payment-page {
  padding: 20px;
  background-color: #fff;
  text-align: center;

  button {
    margin-top: 20px;
  }
}




/* 新增的样式 */
.order-details {
  font-size: 14rem;
  padding: 8rem 15rem;
  margin-top: 10rem;
  border-top: 1rem solid #d1cdcd;

  div {
    margin-top: 15rem;
  }
}

.order-details span {
  margin-right: 30rem;
}

.order-details input[type="radio"] {
  margin-left: 71rem;
}

.order-details input[type="text"] {
  width: 260rem;
  border: none;
  background-color: #f7f7f7;
  font-size: 12rem;
  padding: 5rem;
  border-radius: 5rem;
}

.total-price {
  margin: 10rem 0rem 15rem 220rem;
  font-size: 14rem;
  color: red;
  font-weight: bold;
}
</style>
